from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
import os

from .config import settings
from .database import engine, Base
from .api import api_router
from .models import User
from .auth.auth import get_password_hash

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.VERSION,
    description="集用户身份认证、智能问答、知识库管理、智能写作于一体的轻量级大模型应用平台"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOW_ORIGINS,
    allow_credentials=settings.ALLOW_CREDENTIALS,
    allow_methods=settings.ALLOW_METHODS,
    allow_headers=settings.ALLOW_HEADERS,
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="../frontend/static"), name="static")

# 为了兼容性，添加直接的CSS和JS路由
app.mount("/css", StaticFiles(directory="../frontend/static/css"), name="css")
app.mount("/js", StaticFiles(directory="../frontend/static/js"), name="js")

# 模板配置
templates = Jinja2Templates(directory="../frontend")

# 包含API路由
app.include_router(api_router, prefix="/api")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    """主页 - 登录页面"""
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
    """仪表板页面"""
    return templates.TemplateResponse("dashboard.html", {"request": request})

@app.get("/pages/{page_name}", response_class=HTMLResponse)
async def serve_page(request: Request, page_name: str):
    """动态页面服务"""
    page_path = f"pages/{page_name}.html"
    if os.path.exists(f"../frontend/{page_path}"):
        return templates.TemplateResponse(page_path, {"request": request})
    else:
        return templates.TemplateResponse("404.html", {"request": request}, status_code=404)

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    print(f"🚀 {settings.APP_NAME} v{settings.VERSION} 启动成功!")
    print(f"📖 API文档: http://localhost:8000/docs")
    print(f"🌐 前端页面: http://localhost:8000")
    
    # 创建默认用户
    from .database import SessionLocal
    db = SessionLocal()
    
    # 检查是否存在默认用户
    admin_user = db.query(User).filter(User.username == "admin").first()
    if not admin_user:
        # 创建默认管理员用户
        admin_user = User(
            username="admin",
            email="admin@example.com",
            full_name="管理员",
            hashed_password=get_password_hash("admin"),
            is_admin=True,
            is_active=True
        )
        db.add(admin_user)
        db.commit()
        print("✅ 已创建默认用户: admin / admin")
    else:
        print("ℹ️ 默认用户已存在: admin / admin")
    
    db.close()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 